//
//  CitiesViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/15.
//

import UIKit
import RxSwift
import RxCocoa
struct AreaModel: Codable {
    let genteel: Int
    let openly: String
    let th: String
    let mourned: String?
    let teach: [AreaModel]?
    let level: Int
    init(from decoder: any Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.genteel = try container.decode(Int.self, forKey: .genteel)
        self.openly = try container.decode(String.self, forKey: .openly)
        self.th = try container.decode(String.self, forKey: .th)
        self.mourned = try container.decodeIfPresent(String.self, forKey: .mourned)
        self.teach = try container.decodeIfPresent([AreaModel].self, forKey: .teach)
        if self.openly.count == 4 {
            self.level = 1
        } else if self.openly.count == 8 {
            self.level = 2
        } else if self.openly.count == 12 {
            self.level = 3
        } else {
            self.level = 4
        }
    }
}

class CitiesViewController: UIViewController {

    let bag = DisposeBag()
    
    var choosenAreas: [AreaModel?] = []//用于初始化时选中状态
    
    let confirmArea = PublishSubject<[AreaModel?]>()
    
    @IBOutlet weak var tableView: UITableView!
    
    private var areas: [AreaModel] = []
    
    private let currentArea = BehaviorRelay<AreaModel?>.init(value: nil)
    
    private let province = BehaviorRelay<AreaModel?>.init(value: nil)
    
    private let city = BehaviorRelay<AreaModel?>.init(value: nil)
    
    private let area = BehaviorRelay<AreaModel?>.init(value: nil)
    
    @IBOutlet weak var firstAreaButton: UIButton!
    
    @IBOutlet weak var firstSeparatorView: UIView!
    @IBOutlet weak var secondAreaButton: UIButton!
    
    @IBOutlet weak var secondSeparatorView: UIView!
    @IBOutlet weak var thirdAreaButton: UIButton!
    
    @IBOutlet weak var thirdSeparatorView: UIView!
    @IBOutlet weak var separatorView: UIView!
    
    @IBOutlet weak var confirmButton: UIButton!
    
    @IBAction func closeAction(_ sender: UIButton) {
        self.dismiss(animated: false)
    }
    
    @IBAction func confirmAction(_ sender: UIButton) {
        let p = self.province.value
        let c = self.city.value
        let a = self.area.value
        self.confirmArea.onNext([p, c, a])
        self.dismiss(animated: false)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
        // Do any additional setup after loading the view.
    }

    private func configView() {
        let url = URL(fileURLWithPath: NSHomeDirectory() + "provinces.dat", isDirectory: false)
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let arr = try decoder.decode([AreaModel].self, from: data)
            self.areas = arr
            self.tableView.reloadData()
        } catch {
            
        }
        let title = NSAttributedString(string: "Select".locale, attributes: [.foregroundColor: UIColor.color(with: 18, green: 16, blue: 17), .font: UIFont.systemFont(ofSize: 16, weight: .medium)])
        self.firstAreaButton.setAttributedTitle(title, for: .normal)
        self.currentArea
            .subscribe(onNext: { [weak self] model in
                if let subAreas = model?.teach {
                    if model?.level == 1 {
                        self?.province.accept(model)
                    } else if model?.level == 2 {
                        self?.city.accept(model)
                    } else if model?.level == 3 {
                        self?.area.accept(model)
                    }
                    self?.areas = subAreas
                } else {
                    self?.area.accept(model)
                }
                self?.tableView.reloadData()
            })
            .disposed(by: self.bag)
        GlobalNotifier.default.provinces
            .subscribe(onNext: { [weak self] array in
                self?.areas = array
                self?.tableView.reloadData()
                if self!.choosenAreas.count > 0 {
                    if let province = self?.choosenAreas[0] {
                        self?.province.accept(province)
                        self?.currentArea.accept(province)
                    }
                }
                if self!.choosenAreas.count > 1 {
                    if let city = self?.choosenAreas[1] {
                        self?.city.accept(city)
                        self?.currentArea.accept(city)
                    }
                }
                if self!.choosenAreas.count > 2 {
                    if let area = self?.choosenAreas[2] {
                        self?.area.accept(area)
                        self?.currentArea.accept(area)
                    }
                }
            })
            .disposed(by: self.bag)
        self.tableView.separatorStyle = .none
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.register(UINib(nibName: "AddressTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "AddressTableViewCell")
        
        self.province
            .filter({$0 != nil})
            .subscribe(onNext: { [weak self] area in
                let title = NSAttributedString(string: area!.th, attributes: [.foregroundColor: UIColor.color(with: 18, green: 16, blue: 17), .font: UIFont.systemFont(ofSize: 16, weight: .medium)])
                self?.firstAreaButton.setAttributedTitle(title, for: .normal)
                self?.firstAreaButton.isHidden = false
                self?.secondAreaButton.isHidden = true
                self?.thirdAreaButton.isHidden = true
                self?.firstSeparatorView.isHidden = false
                self?.secondSeparatorView.isHidden = true
                self?.thirdSeparatorView.isHidden = true
            })
            .disposed(by: self.bag)
        self.city
            .filter({$0 != nil})
            .subscribe(onNext: { [weak self] area in
                let normalTitle = NSAttributedString(string: self!.province.value!.th, attributes: [.foregroundColor: UIColor.color(with: 18, green: 16, blue: 17), .font: UIFont.systemFont(ofSize: 16)])
                let choosedTitle = NSAttributedString(string: area!.th, attributes: [.foregroundColor: UIColor.color(with: 18, green: 16, blue: 17), .font: UIFont.systemFont(ofSize: 16, weight: .medium)])
                self?.firstAreaButton.setAttributedTitle(normalTitle, for: .normal)
                self?.secondAreaButton.setAttributedTitle(choosedTitle, for: .normal)
                self?.firstAreaButton.isHidden = false
                self?.secondAreaButton.isHidden = false
                self?.thirdAreaButton.isHidden = true
                self?.firstSeparatorView.isHidden = true
                self?.secondSeparatorView.isHidden = false
                self?.thirdSeparatorView.isHidden = true
            })
            .disposed(by: self.bag)
        self.area
            .filter({$0 != nil})
            .subscribe(onNext: { [weak self] area in
                let normalProvinceTitle = NSAttributedString(string: self!.province.value!.th, attributes: [.foregroundColor: UIColor.color(with: 18, green: 16, blue: 17), .font: UIFont.systemFont(ofSize: 16)])
                let normalCityTitle = NSAttributedString(string: self!.city.value!.th, attributes: [.foregroundColor: UIColor.color(with: 18, green: 16, blue: 17), .font: UIFont.systemFont(ofSize: 16)])
                let choosedTitle = NSAttributedString(string: area!.th, attributes: [.foregroundColor: UIColor.color(with: 18, green: 16, blue: 17), .font: UIFont.systemFont(ofSize: 16, weight: .medium)])
                self?.firstAreaButton.setAttributedTitle(normalProvinceTitle, for: .normal)
                self?.secondAreaButton.setAttributedTitle(normalCityTitle, for: .normal)
                self?.thirdAreaButton.setAttributedTitle(choosedTitle, for: .normal)
                self?.firstAreaButton.isHidden = false
                self?.secondAreaButton.isHidden = false
                self?.thirdAreaButton.isHidden = false
                
                self?.firstSeparatorView.isHidden = true
                self?.secondSeparatorView.isHidden = true
                self?.thirdSeparatorView.isHidden = false
            })
            .disposed(by: self.bag)
        
        self.firstAreaButton.rx.tap
            .subscribe { [weak self] _ in
                self?.currentArea.accept(self?.province.value)
            }
            .disposed(by: self.bag)
        self.secondAreaButton.rx.tap
            .subscribe { [weak self] _ in
                self?.currentArea.accept(self?.city.value)
            }
            .disposed(by: self.bag)
        self.thirdAreaButton.rx.tap
            .subscribe { [weak self] _ in
                self?.currentArea.accept(self?.area.value)
            }
            .disposed(by: self.bag)
        Observable.combineLatest(self.province, self.city, self.area)
            .map({ province, city, area in
                return province != nil && city != nil && area != nil
            })
            .bind(to: self.confirmButton.rx.isEnabled)
            .disposed(by: self.bag)
    }

}

extension CitiesViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.areas.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AddressTableViewCell") as! AddressTableViewCell
        let area = self.areas[indexPath.row]
        cell.area = area
        cell.choosed = self.currentArea.value?.openly == area.openly
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.areas[indexPath.row]
        self.currentArea.accept(model)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
}
